<template>
  <div>
    <div v-if="!showEditor" style="width: 100%; height: 100%">
      <div id="container" style="width: 100%; height: 100%; position: relative" />
      <div class="input-card" style="position: absolute; top: 30px; left: 10px">
        <h4>轨迹回放控制</h4>
        <div class="input-item">
          <input type="button" class="btn" value="开始" @click="startAnimation" />
          <input type="button" class="btn" value="暂停" @click="pauseAnimation" />
        </div>
        <div class="input-item">
          <input type="button" class="btn" value="继续" @click="resumeAnimation" />
          <input type="button" class="btn" value="停止" @click="stopAnimation" />
        </div>
        <input type="button" class="btn" value="查看设备" @click="showEditorBtn" />
      </div>
    </div>
    <div v-if="showEditor" style="width: 100%; height: 100%; position: relative">
      <Editor @close="showEditor = false" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue"
import { getTokenApi, getCoordinateApi } from "@/api/coordinate"

import Editor from "./Editor.vue"
const showEditor = ref(false)
const showEditorBtn = () => {
  showEditor.value = true
}
let map, marker, polyline, passedPolyline, circle, startCircle
const lineArr = ref([
  [116.478935, 39.997761],
  [116.478939, 39.997825],
  [116.478912, 39.998549],
  [116.478998, 39.998555],
  [116.479282, 39.99856],
  [116.479658, 39.998528],
  [116.480151, 39.998453],
  [116.480784, 39.998302],
  [116.481149, 39.998184],
  [116.481573, 39.997997],
  [116.481863, 39.997846],
  [116.482072, 39.997718],
  [116.482362, 39.997718],
  [116.483633, 39.998935],
  [116.48367, 39.998968],
  [116.484648, 39.999861]
])

const circleCenter = [116.480784, 39.998302] // 圆心
const circleRadius = 100 // 电子围栏半径
const alertDistance = 500 // 警报距离
const startCircleRadius = 30 // 起点电子围栏半径

const isInsideFence = ref(false)
let stayTimer: any = null
let outsideTimer: any = null

// 初始化地图
const initMap = () => {
  map = new AMap.Map("container", {
    resizeEnable: true,
    center: [116.478935, 39.997761],
    zoom: 16
  })

  // 创建Marker
  marker = new AMap.Marker({
    map: map,
    position: lineArr.value[0],
    icon: "https://webapi.amap.com/images/car.png",
    offset: new AMap.Pixel(-26, -13),
    autoRotation: true,
    angle: -90
  })

  // 创建轨迹线
  polyline = new AMap.Polyline({
    map: map,
    path: lineArr.value,
    showDir: true,
    strokeColor: "#28F",
    strokeWeight: 6
  })

  // 创建已经经过的路径线
  passedPolyline = new AMap.Polyline({
    map: map,
    strokeColor: "#AF5",
    strokeWeight: 6
  })

  // 绘制电子围栏（圆形）
  circle = new AMap.Circle({
    center: circleCenter,
    radius: circleRadius,
    strokeColor: "#FF33FF", // 边线颜色
    strokeWeight: 2,
    fillColor: "#FF99FF", // 填充颜色
    fillOpacity: 0.5
  })

  // 创建起点电子围栏
  startCircle = new AMap.Circle({
    center: lineArr.value[0], // 设置为轨迹的起点
    radius: startCircleRadius,
    strokeColor: "#FFFF00", // 边线颜色：黄色
    strokeWeight: 2,
    fillColor: "#FFFF00", // 填充颜色：黄色
    fillOpacity: 0.5
  })

  map.add(circle)
  map.add(startCircle) // 将起点电子围栏添加到地图

  marker.on("moving", (e) => {
    passedPolyline.setPath(e.passedPath)
    const position = marker.getPosition()
    const isInFence = circle.contains(position) // 检查是否在电子围栏内

    // 进入电子围栏
    if (isInFence && !isInsideFence.value) {
      isInsideFence.value = true
      alert("车辆进入电子围栏！")
      clearOutsideTimer() // 清除外部停留计时器
      startStayTimer() // 开始停留计时器
    }

    // 离开电子围栏
    if (!isInFence && isInsideFence.value) {
      isInsideFence.value = false
      alert("车辆离开电子围栏！")
      clearStayTimer() // 清除停留计时器
      startOutsideTimer() // 开始外部计时
    }

    // 如果离开电子围栏，但仍在 500 米范围内
    if (!isInFence) {
      const distanceToFence = AMap.GeometryUtil.distance(position, circleCenter)
      if (distanceToFence > circleRadius && distanceToFence <= circleRadius + alertDistance) {
        // 开始外部计时器
        if (!outsideTimer) {
          startOutsideTimer()
        }
      } else {
        clearOutsideTimer() // 超出范围时清除计时器
      }
    }
  })

  map.setFitView()
}

// 开始停留计时器
const startStayTimer = () => {
  stayTimer = setTimeout(() => {
    alert("停留超时！")
    clearStayTimer() // 停止计时器，只触发一次告警
  }, 8000) // 15秒
}

// 清除停留计时器
const clearStayTimer = () => {
  if (stayTimer) {
    clearTimeout(stayTimer)
    stayTimer = null
  }
}

// 开始外部停留计时器
const startOutsideTimer = () => {
  outsideTimer = setTimeout(() => {
    const position = marker.getPosition()
    const distanceToFence = AMap.GeometryUtil.distance(position, circleCenter)
    alert(`车辆距离电子围栏 ${distanceToFence.toFixed(2)} 米，疑似无计划作业！`)
    clearOutsideTimer() // 停止计时器，只触发一次告警
  }, 8000) // 15秒
}

// 清除外部停留计时器
const clearOutsideTimer = () => {
  if (outsideTimer) {
    clearTimeout(outsideTimer)
    outsideTimer = null
  }
}

// 动画控制
const startAnimation = () => {
  marker.moveAlong(lineArr.value, 200)
  alert(`无计划作业车辆！`)
  console.log("开始动画")
}

const pauseAnimation = () => {
  marker.pauseMove()
}

const resumeAnimation = () => {
  marker.resumeMove()
}

const stopAnimation = () => {
  marker.stopMove()
  clearStayTimer() // 停止时清除停留计时器
  clearOutsideTimer() // 停止时清除外部停留计时器
}

// 定义一个函数调用 API 获取 token
const fetchTokenAndCoordinates = async () => {
  try {
    const response = await getTokenApi(username.value, password.value) // 调用接口并传入参数
    token.value = response.data.token // 假设接口返回的 token 在 response.token 中
    console.log(token.value, "token")

    // 在获取到 token 后，立即调用 getCoordinateApi
    if (token.value) {
      const coordinatesResponse = await getCoordinateApi(token.value, page.value, pageSize.value)
      coordinates.value = coordinatesResponse.data.records

      // 去重并转换经纬度数据
      const uniqueCoordinates = new Set()

      lineArr.value = coordinates.value
        .map((coordinate) => {
          const longitude = coordinate.longitude.split(" ")[0] // 去掉 " E"
          const latitude = coordinate.latitude.split(" ")[0] // 去掉 " N"
          const coordPair = `${longitude},${latitude}` // 将经纬度转换为字符串
          if (!uniqueCoordinates.has(coordPair)) {
            // 检查是否已存在该坐标对
            uniqueCoordinates.add(coordPair) // 如果不存在，加入 Set 中
            return [parseFloat(longitude), parseFloat(latitude)] // 返回 [longitude, latitude] 数组
          }
          return null // 如果是重复的，返回 null
        })
        .filter((item) => item !== null) // 过滤掉重复项 (null)
      initMap() // 重新初始化地图
    }
  } catch (err) {
    error.value = "Failed to fetch token or coordinates"
    console.error(err) // 输出错误信息以便调试
  }
}

// 登录处理函数
const handleLogin = async () => {
  await fetchTokenAndCoordinates() // 调用获取 token 和坐标的函数
  console.log(lineArr.value, "去重后的坐标数据")
}

// 挂载时初始化地图
onMounted(() => {
  initMap()
})
</script>

<style scoped>
#container {
  width: 100%;
  height: 500px;
}

.input-card .btn {
  margin-right: 1.2rem;
  width: 6rem;
}

.input-card .btn:last-child {
  margin-right: 0;
  margin-top: 6px;
}
</style>
